<?php
namespace app\admin\controller;

use app\admin\model\WebsetModel;

class Webset extends Base
{
	public function index(){
		$sysInfo = [
			'framework' => "thinkPHP ".THINK_VERSION,
			'php_version' => phpversion(),
			'mysql_version' => db()->query('select version() as v;')[0]['v'],
			'web_run_environment' => php_sapi_name(),
			'server_os' => php_uname(),
		];
		$this->assign([
			'sysInfo' => $sysInfo,
		]);
		return $this->fetch();
	}

	public function subForm(){
		$params = input('post.');
		$model = new WebsetModel();
		$websets = $model->select()->toArray();
		$model::startTrans();
		try{
			foreach($params as $k => $v){
				$info = $model->where('name',$k)->find()->toArray();
				switch ($info['type']) {
					case '0': # 仅更新数据库
						$model->where('name',$k)->update(['values'=>$v]);
						break;
					case '1': # Array
						$old_arr = explode('-',$info['values']);
						$oldArrStr = '[';
						foreach($old_arr as $xx => $ee){
							if($xx == (sizeof($old_arr)-1)){
								$oldArrStr .= "'".$ee."']";
							}else{
								$oldArrStr .= "'".$ee."',";
							}
						}
						$new_arr = explode('-',$v);
						$newArrStr = '[';
						foreach($new_arr as $xx => $ee){
							if($xx == (sizeof($new_arr)-1)){
								$newArrStr .= "'".$ee."']";
							}else{
								$newArrStr .= "'".$ee."',";
							}
						}
						$old_str = "'" . $k . "' => " . $oldArrStr;
						$new_str = "'" . $k . "' => " . $newArrStr;
						$this->editConfigFile($k,$v,$old_str,$new_str);
						break;
					case '2': # 值不需要加引号
						$old_str = "'" . $k . "' => " . $info['values'];
						$new_str = "'" . $k . "' => " . $v;
						$this->editConfigFile($k,$v,$old_str,$new_str);
						break;
					case '3': # 值需要加引号
						$old_str = "'" . $k . "' => '" . $info['values'] . "'";
						$new_str = "'" . $k . "' => '" . $v . "'";
						$this->editConfigFile($k,$v,$old_str,$new_str);
						break;
				}
			}
			$model::commit();
			return ['code'=>1,'msg'=>'保存成功'];
		}catch(Exception $e){
			$model::rollback();
			return ['code'=>0,'msg'=>'保存失败'.$e->getMessage()];
		}
	}

	public function editConfigFile($k,$v,$old_str,$new_str) {
		$model = new WebsetModel();
		$configurl = __DIR__.'../../../config.php';
		$origin_str = file_get_contents($configurl);
		$update_str = str_replace($old_str,$new_str,$origin_str);
		file_put_contents($configurl,$update_str);
		$model->where('name',$k)->update(['values'=>$v]);
	}

}
